/*
 * Project: BoboDesignPattern
 * 
 * File Created at 2019年9月14日
 * 
 * Copyright 2012 Greenline.com Corporation Limited.
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of
 * Greenline Company. ("Confidential Information").  You shall not
 * disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license agreement you entered into
 * with Greenline.com.
 */
package test.scattered2.myrpc.server;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Method;
import java.net.Socket;

/**
 * @Type ProcessorHandler
 * @Desc
 * @author 52489
 * @date 2019年9月14日
 * @Version V1.0
 */
public class ProcessorHandler implements Runnable {
    Socket socket;
    Object service;

    /**
     * @param socket
     * @param service
     */
    public ProcessorHandler(Socket socket, Object service) {
        super();
        this.socket = socket;
        this.service = service;
    }

    /*
     * (non-Javadoc)
     * 
     * @see java.lang.Runnable#run()
     */
    @Override
    public void run() {
        System.out.println("开始处理客户端请求");
        ObjectInputStream inputStream = null;

        try {
            inputStream = new ObjectInputStream(socket.getInputStream());
            RPCRequest rpcRequest = (RPCRequest) inputStream.readObject();
            Object result = invoke(rpcRequest);
            ObjectOutputStream outputStream = new ObjectOutputStream(socket.getOutputStream());
            outputStream.writeObject(result);
            outputStream.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // if (condition) {
            //
            // }
        }

    }

    private Object invoke(RPCRequest request) throws Exception {
        Object[] args = request.getParameters();
        Class[] types = new Class[args.length];
        for (int i = 0; i < types.length; i++) {
            types[i] = args[i].getClass();
        }
        Method method;
        method = service.getClass().getMethod(request.getMethodName(), types);
        Object result = method.invoke(service, args);
        return result;
    }

}
